package net.cathackers.devel.scmp.chat.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import net.cathackers.devel.scmp.chat.impl.xmpp.iqcomponent.interfaces.Processor;
import net.cathackers.devel.scmp.chat.interfaces.ManagedQueue;

public class ManagedQueueImpl<T> implements ManagedQueue<T> {
    protected BlockingQueue<Runnable> queue_;
    protected ThreadPoolExecutor executor_;
    protected Processor<T> processor_;
    private int corePoolSize_;
    private int maximumPoolSize_;
    private long keepAliveTime_ = 3000;

    public ManagedQueueImpl(Processor<T> processor, int corePoolSize) {
	processor_ = processor;
	queue_ = new LinkedBlockingQueue<Runnable>(5000);
	corePoolSize_ = corePoolSize;
	maximumPoolSize_ = corePoolSize;
	executor_ = new ThreadPoolExecutor(corePoolSize_, maximumPoolSize_,
		keepAliveTime_, TimeUnit.MILLISECONDS, queue_);
    }

    public void enqueue(final T t) {
	Runnable runnable = new Runnable() {
	    public void run() {
		processor_.process(t);
	    }
	};
	executor_.execute(runnable);
    }

    public int getSize() {
	return queue_.size();
    }

    public Processor<T> getProcessor() {
	return processor_;
    }

    public boolean isRunning() {
	boolean ret = true;
	if (executor_.isShutdown()) {
	    ret = false;
	}
	return ret;
    }

    public boolean setProcessor(Processor<T> processor) {
	boolean ret = false;
	if (processor != null) {
	    processor_ = processor;
	    ret = true;
	}
	return ret;
    }

    public void stop() {
	executor_.shutdown();
    }

    public long getCompletedTaskcount() {
	return executor_.getCompletedTaskCount();
    }

    public void setMaxPoolSize(int max) {
	maximumPoolSize_ = max;
    }

    public void setKeepAliveTime(long time) {
	keepAliveTime_ = time;
    }

    public long getscheduledTaskCount() {
	return executor_.getTaskCount();
    }

}
